package main

import (
	"fmt"
	"net/http"

	"github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
	ReadBufferSize: 1024,
	WriteBufferSize: 1024,
	// 默认跨域检查是阻止的，这里关闭检查允许所有来源
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func main(){
	// WebSocket 路由：回显客户端发送的消息
	http.HandleFunc("/echo",func(w http.ResponseWriter, r *http.Request) {
		// 将 HTTP 请求升级为 WebSocket 连接
		conn,err := upgrader.Upgrade(w,r,nil)
		if err != nil {
			http.Error(w, "Could not open websocket connection", http.StatusBadRequest)
			return
		}

		// 不断读取回显的消息
		for{
			msgType,msg,err := conn.ReadMessage()
			if err != nil {
				fmt.Println("Read error:", err)
				return
			}
			fmt.Printf("%s sent: %s\n", conn.RemoteAddr(), string(msg))

			// 回显消息
			if err := conn.WriteMessage(msgType, msg); err != nil {
				fmt.Println("Write error:", err)
				return
			}
		}

	})

	// 提供 HTML 页面
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, "websockets.html")
	})

	// 启动服务器
	fmt.Println("Server listening on http://localhost:8080")
	http.ListenAndServe(":8080", nil)

}